#include "user_timers.h"
#include "sw_interrupt.h"
#include "os_io.h"
#include "os_mem.h"


err_t user_timer_start(user_timer_data_t *timer_data)
{
    //printf("Received timer with interval: 0x%x\n", timer_data->interval);
    // perform validations
    if (!timer_data) {
        printf("NULL timer data passed\n");
        return ERR_INVALID;
    }

    if (!timer_data->interval) {
        printf("Invalid timer interval passed: 0x%x\n", timer_data->interval);
        return ERR_INVALID;
    } 

    timer_data->state = TIMER_REQUESTED;

    raise_sw_interrupt(SW_INT_TIMER_START, (uint32_t)timer_data);

    return timer_data->timer_err;
}

err_t user_timer_cancel(user_timer_data_t *timer_handle)
{
    err_t err_code;

    if (!timer_handle) {
        return ERR_INVALID;
    }

    raise_sw_interrupt(SW_INT_TIMER_CANCEL, (uint32_t)timer_handle);

    err_code = timer_handle->timer_err;
    if (err_code == ERR_SUCCESS) {
        if (timer_handle->state != TIMER_CANCELLED) {
	    // timer was still running in platform
	    free(timer_handle);
	} else {
	    // Timer already got expired, and is in our queue.
	    // Do not free it here. it shall get freed during dequeue
	}
    }

    return err_code;
}
    


